package cn.tedu._03_vehicle.controller;

import cn.tedu._03_vehicle.base.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.AttributedCharacterIterator;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file/")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file ) throws IOException {//用这个文件对象去接
        //将图片保存到服务器：d:/files/2025/03/11/xxx.jpg
        //返回响应{"state":2000,"message":"操作成功","data":"/2025/03/11/xxx.jpg"}
        //前端：http://localhost:8080/2005/03/11/xxx.jpg
        //处理文件名
        String originalFilename = file.getOriginalFilename();//获取原始文件名xxx.jpg
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));//将.jpg分割出来
        //运用这个方法，生成随机名字并拼接上.jpg
        originalFilename= UUID.randomUUID()+substring;//42cecf74-6386-4fc2-a778-660c1a23dd4a.jpg
        System.out.println(originalFilename);//边写边测试42cecf74-6386-4fc2-a778-660c1a23dd4a.jpg

        //定义拼接上盘符
        String dirPath = "d:/files";
        //定义时间文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        //迭代出来，用于创建目录所需要的名字
        AttributedCharacterIterator datePath = sdf.formatToCharacterIterator(new Date());
        //保存文件，需要有路径，如果没有路径，则要创建路径
        //创建目录：d:/files/2025/3/11/
        File file1 = new File(dirPath + datePath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        //保存文件：d:/files/2025/3/11/42cecf74-6386-4fc2-a778-660c1a23dd4a.jpg
        String filePath = dirPath + datePath + originalFilename;
        file.transferTo(new File(filePath));
        //再把这三者给拼接起来
        System.out.println(dirPath + datePath + originalFilename);
        return JsonResult.ok(dirPath + datePath + originalFilename);
    }
}
























